#!/usr/bin/env python3
"""
Task Analysis Script - Converted from task_analysis.ipynb
"""

import os
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
from dateutil.parser import parse

# Add the parent directory to the path so we can import the models
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from models.task_predictor import TaskPredictor

# Set the style for plots
plt.style.use('ggplot')
sns.set(style="whitegrid")

def main():
    print("Task Analysis Script - Starting")
    
    # Load the data
    print("\n1. Loading data...")
    data_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 
                            'data', 'task_data_template.csv')
    df = pd.read_csv(data_path)
    print(f"Data loaded: {len(df)} records")
    print(df.head())
    
    # Data exploration
    print("\n2. Data exploration:")
    print(f"Data shape: {df.shape}")
    print("\nData types:")
    print(df.dtypes)
    print("\nSummary statistics:")
    print(df.describe())
    
    # Convert date to datetime
    df['date'] = pd.to_datetime(df['date'])
    
    # Data visualization
    print("\n3. Data visualization:")
    print("Creating plots...")
    
    # Plot 1: Task completion over time
    plt.figure(figsize=(12, 6))
    plt.plot(df['date'], df['planned_tasks'], 'b-', label='Planned Tasks')
    plt.plot(df['date'], df['completed_tasks'], 'g-', label='Completed Tasks')
    plt.title('Task Planning and Completion Over Time')
    plt.xlabel('Date')
    plt.ylabel('Number of Tasks')
    plt.legend()
    plt.tight_layout()
    plt.savefig(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 
                            'output', 'task_completion_over_time.png'))
    print("- Task completion over time plot saved")
    
    # Plot 2: Completion rate by day of week
    plt.figure(figsize=(10, 6))
    sns.boxplot(x='day_of_week', y='completion_rate', data=df)
    plt.title('Task Completion Rate by Day of Week')
    plt.xlabel('Day of Week (1=Monday, 7=Sunday)')
    plt.ylabel('Completion Rate')
    plt.tight_layout()
    plt.savefig(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 
                            'output', 'completion_rate_by_day.png'))
    print("- Completion rate by day of week plot saved")
    
    # Plot 3: Relationship between planned tasks and completion rate
    plt.figure(figsize=(10, 6))
    sns.scatterplot(x='planned_tasks', y='completion_rate', data=df)
    plt.title('Relationship Between Planned Tasks and Completion Rate')
    plt.xlabel('Number of Planned Tasks')
    plt.ylabel('Completion Rate')
    plt.tight_layout()
    plt.savefig(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 
                            'output', 'planned_vs_completion_rate.png'))
    print("- Planned tasks vs completion rate plot saved")
    
    # Model training
    print("\n4. Model training:")
    
    # Prepare features and target
    X = df[['day_of_week', 'is_holiday', 'planned_tasks']].values
    y = df['completion_rate'].values
    
    # Create and train the model
    model = TaskPredictor(input_dim=3)
    history = model.train(X, y, epochs=100, verbose=0)
    print("Model trained successfully")
    
    # Plot training history
    plt.figure(figsize=(10, 6))
    plt.plot(history.history['loss'])
    plt.title('Model Loss During Training')
    plt.xlabel('Epoch')
    plt.ylabel('Loss')
    plt.tight_layout()
    plt.savefig(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 
                            'output', 'model_training_loss.png'))
    print("- Model training loss plot saved")
    
    # Task recommendation
    print("\n5. Task recommendation:")
    
    # Generate predictions for different task counts
    day_of_week = 3  # Wednesday
    is_holiday = 0   # Not a holiday
    task_counts = np.arange(1, 21)  # 1 to 20 tasks
    
    predictions = []
    for task_count in task_counts:
        input_data = np.array([[day_of_week, is_holiday, task_count]])
        pred = model.predict(input_data)[0][0]
        predictions.append(pred)
    
    # Find the optimal task count
    productivity = task_counts * predictions  # Tasks × Completion Rate = Expected Completed Tasks
    optimal_index = np.argmax(productivity)
    optimal_tasks = task_counts[optimal_index]
    optimal_completion = predictions[optimal_index]
    expected_completed = productivity[optimal_index]
    
    print(f"Optimal task count for Wednesday (non-holiday): {optimal_tasks}")
    print(f"Expected completion rate: {optimal_completion:.2f}")
    print(f"Expected completed tasks: {expected_completed:.2f}")
    
    # Plot predictions
    plt.figure(figsize=(12, 6))
    
    plt.subplot(1, 2, 1)
    plt.plot(task_counts, predictions, 'b-o')
    plt.axvline(x=optimal_tasks, color='r', linestyle='--', label=f'Optimal: {optimal_tasks} tasks')
    plt.title('Predicted Completion Rate by Task Count')
    plt.xlabel('Number of Planned Tasks')
    plt.ylabel('Predicted Completion Rate')
    plt.legend()
    
    plt.subplot(1, 2, 2)
    plt.plot(task_counts, productivity, 'g-o')
    plt.axvline(x=optimal_tasks, color='r', linestyle='--', label=f'Optimal: {optimal_tasks} tasks')
    plt.title('Expected Completed Tasks by Task Count')
    plt.xlabel('Number of Planned Tasks')
    plt.ylabel('Expected Completed Tasks')
    plt.legend()
    
    plt.tight_layout()
    plt.savefig(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 
                            'output', 'task_optimization.png'))
    print("- Task optimization plot saved")
    
    print("\nAnalysis complete! Results saved to the output directory.")

if __name__ == "__main__":
    # Create output directory if it doesn't exist
    output_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'output')
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    main()